package cn.rjzjh.tapestry.busi;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;

import javax.servlet.ServletContext;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.ServletContextAware;

import cn.rjzjh.commons.util.thread.ThreadPool;

public class SpringInit extends PropertyPlaceholderConfigurer implements
		ServletContextAware, ApplicationContextAware {
	public static final Properties conf = new Properties();// config配置参数
	public static volatile String pagePath;// page页面存放的根目录
	public static volatile String webRootPath;// Webroot所在目录
	public static volatile ApplicationContext applicationContext;//在页面上可以通过 @Inject 得到此对象

	@Override
	public void setServletContext(ServletContext servletContext) {
		String realPath = servletContext.getRealPath("/");
		SpringInit.webRootPath = realPath;// 配置根目录　

		String rootPath = Thread.currentThread().getContextClassLoader()
				.getResource(".").getPath();
		String appPackage = servletContext
				.getInitParameter("tapestry.app-package");
		SpringInit.pagePath = String.format("%s%s/pages", rootPath,
				appPackage.replace(".", "/"));
	}

	@SuppressWarnings("static-access")
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

	public static ExecutorService getDefaultPool() {
		return ThreadPool.getDefaultPool(conf);
	}

	/****
	 * 读取属性配置
	 */
	@Override
	protected void processProperties(
			ConfigurableListableBeanFactory beanFactoryToProcess,
			Properties props) throws BeansException {
		Map<String, String> tempMap = new HashMap<String, String>();
		for (Object key : props.keySet()) {
			String keyStr = String.valueOf(key);
			String value = props.getProperty(keyStr);
			tempMap.put(keyStr, value);
		}
		conf.putAll(tempMap);
	}
}
